import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:wu_you/data/api/api.dart';
import 'package:wu_you/data/cache/auth_cache.dart';
import 'package:wu_you/data/cache/username_password_cache.dart';
import 'package:wu_you/http/http.dart';

class AuthRepository{
  factory AuthRepository() => _getInstance();
  static AuthRepository _instance;

  AuthRepository._internal();

  static AuthRepository _getInstance() {
    if (_instance == null) {
      _instance = AuthRepository._internal();
    }
    return _instance;
  }

  ///登录
  Future<dynamic> login(String mobile, String password) async {
    Map<String, dynamic> params = {
      "username": mobile,
      "password": password,
    };
    // Options o = Options();
    // o.headers = {'language':'1'};
    dynamic mapResult = await Http(useToken: false).post(Api.login, data: params);
    Http().token = mapResult;
    //缓存token
    await AuthTokenCache().save(mapResult);
    //缓存账号密码
    UsernamePasswordCache usernamePasswordCache = UsernamePasswordCache();
    await usernamePasswordCache.save(mobile, key: UsernamePasswordCache.KEY_USERNAME);
    await usernamePasswordCache.save(password, key: UsernamePasswordCache.KEY_PASSWORD);
    return mapResult;
  }


  ///注册
  Future<void> register(String username, String password, String code, String pid,String phone) async {
    Map<String, dynamic> data = {
      "username": username,
      "password": password,
      "confirmPasswor":password,
      "code": code,
      "pid":pid,
      "phone":phone
    };
    return await Http(useToken: false).post(Api.register,data: data);
  }

  ///获取验证码
  Future<void> getSmsCode(int type,{String phone}) async {
    ///1,登录 2,注册 3,找回密码 4,修改密码 5,实名认证 6,提现 7,二级密码修改 8 绑定收款码
    Map<String, dynamic> data = {
      "type":type,
      "phone":phone,
    };
    bool use = false;
    if(type == 1 || type == 2 || type == 3){
      use = false;
    }else{
      use = true;
    }
    return await Http(useToken: use).post(Api.smsCode,data: data);
  }

  ///忘记密码
  Future<void> forgetPassword({String username, String password, String code,String phone}) async {
    Map<String, dynamic> data = {
      "username": username,
      "password": password,
      "confirmPasswor":password,
      "code": code,
      "phone":phone
    };
    await Http(useToken: false).post(Api.forgetPwd, data: data);
  }
}